//
//  SelectTextView.m
//  NVAReader
//
//  Created by DuyLK on 6/25/14.
//  Copyright (c) 2014 com.nva.nvareader. All rights reserved.
//

#import "SelectTextView.h"
#include "common.h"
#import "NVAWord.h"
@implementation SelectTextView
@synthesize curves;
@synthesize colorDraw;
- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    }
    return self;
}

- (id) initWithWords:(NSArray *)_words pageSize:(CGSize)_pageSize witdth:(int)widthPage height:(int)heightPage
{
	self = [super initWithFrame:CGRectMake(0,0,widthPage,heightPage)];
	if (self)
	{
        [[NSColor clearColor] setFill];
		words = [_words retain];
		pageSize = _pageSize;
        _widthPage = widthPage -10;
		_heightPage = heightPage -10;
        color = [[NSColor colorWithRed:0x25/255.0 green:0x72/255.0 blue:0xAC/255.0 alpha:0.5] retain];
        
        trackingArea = [[NSTrackingArea alloc] initWithRect:[self frame]
                                                    options: (NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveInKeyWindow )
                                                      owner:self userInfo:nil];
        [self addTrackingArea:trackingArea];
        colorDraw = [[NSColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0] retain];
		curves = [[NSMutableArray array] retain];
    }
	return self;
}

-(void)dealloc
{
	[curves release]; curves = nil;
	[color release]; color = nil;
    //[colorDraw release]; colorDraw = nil;
    [trackingArea release];trackingArea = nil;
    [words release]; words = nil;
	[super dealloc];
}

- (NSArray *) selectionRects
{
	NSMutableArray *arr = [NSMutableArray array];
	__block CGRect r;
    
	[NVAWord selectFrom:start to:end fromWords:words
            onStartLine:^{
                r = CGRectNull;
            } onWord:^(NVAWord *w) {
                r = CGRectUnion(r, w.rect);
            } onEndLine:^{
                if (!CGRectIsNull(r))
                    [arr addObject:[NSValue valueWithRect: NSMakeRect(r.origin.x, r.origin.y,r.size.width,r.size.height)]];
            }];
    
	return arr;
}

- (NSString *) selectedText
{
	__block NSMutableString *text = [NSMutableString string];
	__block NSMutableString *line;
    
	[NVAWord selectFrom:start to:end fromWords:words
            onStartLine:^{
                line = [NSMutableString string];
            } onWord:^(NVAWord *w) {
                if (line.length > 0)
                    [line appendString:@" "];
                [line appendString:w.string];
            } onEndLine:^{
                if (text.length > 0)
                    [text appendString:@"\n"];
                [text appendString:line];
            }];
    
	return text;
}

- (void)drawRect:(NSRect)dirtyRect
{
    [NSGraphicsContext saveGraphicsState];
    
    CGSize scale = fitPageToScreen(pageSize, self.bounds.size);
    CGContextRef cref =  [[NSGraphicsContext currentContext] graphicsPort];
    CGContextScaleCTM(cref, scale.width, scale.height);
    if (_isDraw) {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        if([ud boolForKey:@"ColorDraw"])
        {
            int colorHightLignt = (int) [[NSUserDefaults standardUserDefaults] integerForKey:@"ColorDraw"];
            colorDraw =  colorDecode(colorHightLignt);
        }
        else
        {
            colorDraw = [NSColor redColor];
        }
        [colorDraw set];
        CGContextSetLineWidth(cref, 2.0);
        for (NSArray *curve in curves)
        {
            if (curve.count >= 2)
            {
                NSPoint pt = [[curve objectAtIndex:0] pointValue];
                CGContextBeginPath(cref);
                CGContextMoveToPoint(cref, pt.x, pt.y);
                CGPoint lpt = pt;
                
                for (int i = 1; i < curve.count; i++)
                {
                    pt = [[curve objectAtIndex:i] pointValue];
                    CGContextAddQuadCurveToPoint(cref, lpt.x, lpt.y, (pt.x + lpt.x)/2, (pt.y + lpt.y)/2);
                    lpt = pt;
                }
                
                CGContextAddLineToPoint(cref, pt.x, pt.y);
                CGContextStrokePath(cref);
            }
        }
    }else
    {
        __block CGRect r;
        [color setFill];
        [NVAWord selectFrom:start to:end fromWords:words
                onStartLine:^{
                    r = CGRectNull;
                } onWord:^(NVAWord *w) {
                    r = CGRectUnion(r, w.rect);
                } onEndLine:^{
                    if (!CGRectIsNull(r))
                    {
                        NSRect rectTemp = NSMakeRect(r.origin.x,r.origin.y,r.size.width,r.size.height);
                        [[NSBezierPath bezierPathWithRect:rectTemp] fill];
                    }
                }];
    }
    [super drawRect: dirtyRect];
    [NSGraphicsContext restoreGraphicsState];
}
- (void) setPageSize:(CGSize)s witdth:(int)widthPage height:(int)heightPage
{
	pageSize = s;
    _widthPage = widthPage-10;
    _heightPage = heightPage -10;
	[self setNeedsDisplay:YES];
}

-(void) mouseDown:(NSEvent *)theEvent
{
    NSPoint curPoint = [self convertPoint:[theEvent locationInWindow] fromView:nil];
    CGSize scale = fitPageToScreen(pageSize, self.bounds.size);
	CGPoint p = curPoint;
	p.x /= scale.width;
	p.y /= scale.height;
    if(!_isDraw)
    {
        start = p;
        BOOL keepOn = YES;
        BOOL isInside = YES;
        NSPoint mouseLoc;
        
        while (keepOn) {
            theEvent = [[self window] nextEventMatchingMask: NSLeftMouseUpMask |
                        NSLeftMouseDraggedMask];
            mouseLoc = [self convertPoint:[theEvent locationInWindow] fromView:nil];
            isInside = [self mouse:mouseLoc inRect:[self bounds]];
            
            switch ([theEvent type]) {
                case NSLeftMouseDragged:
                    p = mouseLoc;
                    p.x /= scale.width;
                    p.y /= scale.height;
                    end = p;
                    break;
                case NSLeftMouseUp:
                    keepOn = NO;
                    break;
                default:
                    /* Ignore any other kind of event. */
                    break;
            }
            [self setNeedsDisplay:YES];
        };
    }else
    {
        start = p;
        BOOL keepOn = YES;
        BOOL isInside = YES;
        NSPoint mouseLoc;
        [curves addObject:[NSMutableArray array]];
        while (keepOn) {
            theEvent = [[self window] nextEventMatchingMask: NSLeftMouseUpMask |
                        NSLeftMouseDraggedMask];
            mouseLoc = [self convertPoint:[theEvent locationInWindow] fromView:nil];
            isInside = [self mouse:mouseLoc inRect:[self bounds]];
            
            switch ([theEvent type]) {
                case NSLeftMouseDragged:
                    p = mouseLoc;
                    p.x /= scale.width;
                    p.y /= scale.height;
                    end = p;
                    NSMutableArray *curve = [curves lastObject];
                    [curve addObject:[NSValue valueWithPoint:end]];
                    break;
                case NSLeftMouseUp:
                    keepOn = NO;
                    [_delegate evenEndDraw];
                    break;
                default:
                    break;
            }
            [self setNeedsDisplay:YES];
        };

    }
    return;
    
}
- (BOOL)isFlipped
{
    return YES;
}

-(void) mouseEntered:(NSEvent *)theEvent
{
    if(_isDraw)
    {
        [[NSCursor crosshairCursor] set];
    }else
    {
        [[NSCursor IBeamCursor] set];
    }
}
-(void) mouseExited:(NSEvent *)theEvent
{
    [[NSCursor arrowCursor] set];
}

- (void)updateTrackingAreas {
    [self removeTrackingArea:trackingArea];
    [trackingArea release];
    trackingArea = [[NSTrackingArea alloc] initWithRect:[self frame]
                                                options: (NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveInKeyWindow)
                                                  owner:self userInfo:nil];
    [self addTrackingArea:trackingArea];
}

-(void) cursorUpdate:(NSEvent *)event
{
    if(_isDraw)
    {
        [[NSCursor crosshairCursor] set];
    }else
    {
        [[NSCursor IBeamCursor] set];
    }
}

-(void) setIsDrawTool:(BOOL)isDraw
{
    if(isDraw)
    {
        start = CGPointZero;
        end = CGPointZero;
    }else
    {
        
    }
    _isDraw = isDraw;
    [self setNeedsDisplay:YES];
}
@end
